import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { ButtonGroup, Button, Table, Container } from "reactstrap";
import AppNavbar from "./appNavbar";

const ClientList = () => {
  const [clients, setClients] = useState([]);
  const [query, setQuery] = useState("react");

  useEffect(() => {
    fetchData();
  }, []);

  async function fetchData() {
    const response = await fetch("/clients");
    const body = await response.json();
    setClients(body);
  }

  const handleDelete = async (id) => {
    console.log(clients);
    await fetch(`/clients/${id}`, {
      method: "DELETE",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json",
      },
    }).then(() => {
      const list = [...clients].filter((x) => x.id !== id);
      setClients(list);
    });
  };

  const clientList = clients.map((client) => {
    return (
      <tr key={client.id}>
        <td style={{ whiteSpace: "nowrap" }}>{client.name}</td>
        <td>{client.email}</td>
        <td>
          <ButtonGroup>
            <Button
              size="sm"
              color="primary"
              tag={Link}
              to={"/clients/" + client.id}
            >
              Edit
            </Button>
            <Button
              size="sm"
              color="danger"
              onClick={() => handleDelete(client.id)}
            >
              Delete
            </Button>
          </ButtonGroup>
        </td>
      </tr>
    );
  });

  return (
    <div>
      <AppNavbar />
      <Container fluid>
        <div className="float-right">
          <Button color="success" tag={Link} to="/clients/new">
            Add New Client
          </Button>
        </div>
        <h3>Clients</h3>
        <Table className="mt-4">
          <thead>
            <tr>
              <th width="30%">Name</th>
              <th width="30%">Email</th>
              <th width="40%">Action</th>
            </tr>
          </thead>
          <tbody>{clientList}</tbody>
        </Table>
      </Container>
    </div>
  );
};

export default ClientList;
